/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xmlasm.bo;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import utils.XMLUtils;
import xmlasm.dao.FeedbackDAO;
import xmlasm.dto.Feedbacks;
import xmlasm.sync.FilePathHolder;

/**
 *
 * @author Hoang
 */
public class FeedbackBO {

    public static void loadFeedbackAndMarshall() {
        Feedbacks feedbacks = FeedbackDAO.getAllFeedbacks();
        //Marshall xuong file xml
        XMLUtils.writeObjectToXML(FilePathHolder.getInstance().getFeedbackXMLPath(), feedbacks);
    }

    //Ham nay xoa feedback trong file XML
     public static boolean deleteFeedbackFromXML(int feedbackID) {
        try {
            Document dom = XMLUtils.parseDom(FilePathHolder.getInstance().getFeedbackXMLPath());
            boolean result = deleteFeedbackFromXML(dom, feedbackID);
            if (result) {
                XMLUtils.writeDOMtoXML(FilePathHolder.getInstance().getFeedbackXMLPath(), dom);
            }
            return result;
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(FeedbackBO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(FeedbackBO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FeedbackBO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    private static boolean deleteFeedbackFromXML(Node node, int feedbackID) {
        if (node == null) {
            return false;
        }

        //Xem thu co phai la node feedbackID hay ko
        if (node.getNodeName().equals("feedbackID")) {
            //Neu tim thay
            if (feedbackID == Integer.parseInt(node.getTextContent())) {
                Node feedback = node.getParentNode(); //Di chuyen toi node feedback
                Node feedbacks = feedback.getParentNode(); //Di chuyen toi node feedbacks
                feedbacks.removeChild(feedback);
                return true;
            }
        }

        NodeList childOfNodes = node.getChildNodes();
        for (int i = 0; i < childOfNodes.getLength(); i++) {
            boolean result = deleteFeedbackFromXML(childOfNodes.item(i), feedbackID);
            if (result) {
                return result;
            }
        }
        return false;
    }
}
